package com.asialjim.wechat.apiservice.executor;

import com.asialjim.wechat.apiservice.executor.handler.BaseResponseHandler;
import com.asialjim.wechat.apiservice.executor.handler.HttpResponseProxy;
import com.asialjim.wechat.apiservice.executor.handler.InputStreamResponseHandler;
import com.asialjim.wechat.apiservice.executor.handler.UTF8ResponseHandler;
import com.asialjim.wechat.utils.FileUtil;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Header;
import org.apache.http.HttpHost;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.FileNameMap;
import java.util.Objects;
import java.util.logging.Logger;

/**
 * <h1><em>ASIAL JIM JAVA DOC</em></h1><hr/>
 * <h2>CLASS DESCRIPTION <i>[ NAME: GetApiExecutor ]</i></h2><strong>
 * <p> api executor for get text type response,such as text/plain, text/xml, application/json, application/xml,but not media type
 * </strong><p><p><em>Copyright &copy; Asial Jim Co., LTD</em><hr/>
 *
 * @author Asial Jim &nbsp;&nbsp; <span>Email:<a href="mailto:asialjim@hotmail.com">asialjim@hotmail.com</a> &nbsp;&nbsp; <a href="asialjim@qq.com">asialjim@qq.com</a></span>
 * @version 1.0.0
 * @since 2021/3/1   &nbsp;&nbsp; JDK 8
 */
public class GetApiExecutor extends BaseApiExecutor {
    public GetApiExecutor(HttpHost httpProxy, String domain, String tempFilePath) {
        super(httpProxy, domain,tempFilePath);
    }

    @Override
    protected <T> T doExecute(HttpRequestBase httpRequest, Class<T> responseClass, ContentType responseContentType) throws IOException {
        CloseableHttpClient client = HttpClientBuilder.create().build();
        try {
            CloseableHttpResponse response = client.execute(httpRequest);
            Header contentTypeHeader = response.getEntity().getContentType();

            // download file
            if (responseClass.isAssignableFrom(File.class) && Objects.nonNull(contentTypeHeader)
                    && BaseResponseHandler.contentTypeEqual(ContentType.parse(contentTypeHeader.getValue()),ContentType.APPLICATION_OCTET_STREAM)){

                InputStreamResponseHandler handler = new InputStreamResponseHandler(InputStream.class);
                InputStream inputStream = handler.handleResponse(response);

                String fileName = new HttpResponseProxy(response).getFileName();
                if (StringUtils.isBlank(fileName)) {
                    fileName = String.valueOf(System.currentTimeMillis());
                }


                File tempDirFile = new File(tempFilePath);
                if (!tempDirFile.exists()){
                    boolean mkdirs = tempDirFile.mkdirs();
                    log.info("\r\n\tmake directories result:[{}]",mkdirs);
                }

                if (!tempDirFile.isDirectory()){
                    boolean delete = tempDirFile.delete();
                    log.info("\r\n\tdelete non directory file result:[{}]",delete);
                    boolean mkdirs = tempDirFile.mkdirs();
                    log.info("\r\n\tmake directories result:[{}]",mkdirs);
                }

                log.info("\r\n\tDOWNLOAD FILE[FILE-NAME:{}]", fileName);

                //noinspection unchecked
                return (T) FileUtil.createTmpFile(inputStream, FilenameUtils.getBaseName(fileName), FilenameUtils.getExtension(fileName), tempDirFile);
            }

            UTF8ResponseHandler<T> handler = new UTF8ResponseHandler<>(responseClass,responseContentType);
            T t = handler.handleResponse(response);
            log.info("\r\n\tHTTP GET CLIENT RESULT:[{}]",t);
            return t;
        } finally {
            httpRequest.releaseConnection();
        }
    }
}